// const path = require('path');
const fs = require('fs');
const { ObjectId } = require("mongodb");
const sourceCollection = 'source';
const userProfileCollection = 'userProfile';
const { sourcePath, role: { admin } } = require('../config');
/**
 * 由于历史弥留问题文件存在 /public/images下 source存在 public/source 下 由这个函数转换地址
 * @param {string} path
 * @return {string} newPath
 */
const getSourcePath = (path) => path.replace(/\/\w+\/$/, '/source/');

const downloadSource = (req, res) => {
    const file = req.url.replace('\/downloadSource\/', '');
    console.log(file);
    res.sendFile(`${sourcePath}${file}`)
}

const handleFsRename = (file, res, callback) => {
    const { path, destination, originalname } = file;

    const sourcePath = getSourcePath(destination);
    const newPath = `${sourcePath}${originalname}`;

    fs.rename(path, newPath, async (err) => {
        if (err) {
            console.error("fs rename err:", err);
            res.status(500).json({ code: -1, message: "文件保存失败" });
        } else { callback() }
    })
}

const createSource = (insertOne) => (req, res) => {
    const File = req.files[0];
    handleFsRename(File, res, async () => {
        const owner = ObjectId(req.userInfo._id);
        const source = { ...req.body, file: File.originalname, owner };
        const item = await insertOne("source", source);
        if (item.insertedId) {
            res.json({ code: 0, message: '资源上传成功', sourceId: item.insertedId });
        } else res.status(500).json({ code: -2, message: "文件保存成功但插入数据库失败" });
    })
}

const querySource = (aggregate) => async (req, res) => {
    const { owner } = req.query;
    const pipeline = [
        {
            $lookup: {
                from: userProfileCollection,
                localField: 'owner',
                foreignField: '_id',
                as: 'sender'
            }
        },
        {
            $project: {
                'sender.password': 0,
                'sender.lastUpdate': 0,
                'sender.thumbsUp': 0,
                'sender.thumbsDown': 0,
                'sender.mail': 0,
            }
        },
        { $sort: { _id: -1 } }
    ];

    if (owner) {
        pipeline.unshift({ $match: { owner: ObjectId(owner) } })
    }

    const sources = await aggregate({ collection: sourceCollection, pipeline });
    console.log(sources);
    res.json({ code: 0, sources })
}

const deleteSource = (findData, deleteOne) => async (req, res) => {
    const { _id } = req.payload;
    const { role, _id: userId } = req.userInfo;

    let pass = false;

    if (role === admin) { pass = true }
    else {
        const [item] = await findData({
            collection: sourceCollection,
            find: { _id: ObjectId(_id) }
        })
        console.log(`找到item:`, item);
        if (item && item.owner.toString() === userId) {
            pass = true;
        }
    }
    if (pass) {
        const result = await deleteOne(sourceCollection, _id);
        console.log("删除资源:", result);
        if (result) res.json({ code: 0, message: "删除资源成功", notification: true })
    } else res.status(500).json({ code: -1, message: "删除失败" })
}

const updateSource = (findData, updateOne) => async (req, res) => {
    const { _id, file, name, description } = req.body;
    const props = { name, description };
    console.log(req.body)
    const { _id: userId, role } = req.userInfo;

    const [source] = await findData({ collection: sourceCollection, find: { _id: ObjectId(_id) } });
    if (!source) return res.status(500).json({ code: -1, message: "未找到资源" }).end();

    const verify = source.owner.toString() === userId || role === admin;
    if (!verify) return res.status(500).json({ code: -2, message: "权限不足" }).end();

    // 没有File上传 只更改 name ,description
    if (file == "null") {
        const update = await updateOne({
            collection: sourceCollection,
            _id, data: props
        });
        console.log("更新结果:", update);
        if (update && update.acknowledged) {
            res.json({ code: 0, message: "更新成功", updateField: { _id, ...props } }).end();
        }
    } else {
        const [File] = req.files;
        // 上传了新的资源
        handleFsRename(File, res, async () => {
            const data = { ...props, file: File.originalname };
            const item = await updateOne({ _id, data, collection: sourceCollection });
            console.log("file update: ", item);

            if (item) {
                res.json({ code: 0, message: '资源上传成功', updateField: { ...data, _id } });
            } else res.status(500).json({ code: -2, message: "文件保存成功但插入数据库失败" });
        })

    }
}

module.exports = {
    createSource,
    querySource,
    downloadSource,
    deleteSource,
    updateSource
}